﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RastinArgham.CRM.Business;
using Mani.Common.Security;

namespace RastinArgham.CRM.Web
{
    public partial class cancelation_items : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();

            if (!securityManager.IsActionPermitted("cancelation_reason"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack)
            {
                LoadCancelationReasons();
            }
        }

        private void LoadCancelationReasons()
        {
            gvCancelationItems.DataSource = crmRepository.GetCancelationReasons();
            gvCancelationItems.DataBind();
        }

        protected void btnSaveChanges_Click(object sender, EventArgs e)
        {
            CancelationReason c = null;

            if (String.IsNullOrEmpty(txtId.Text))
            {
                c = new CancelationReason();
                c.Description = txtDescription.Text;
                crmRepository.AddCancelationReason(c);
            }
            else
            {
                c = crmRepository.GetCancelationReason(Convert.ToInt32(txtId.Text));
                c.Description = txtDescription.Text;
            }

            crmRepository.Save();

            txtId.Text = String.Empty;
            txtDescription.Text = String.Empty;
            LoadCancelationReasons();
        }

        protected void gvCancelationItems_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            CancelationReason c = crmRepository.GetCancelationReason( Convert.ToInt32( gvCancelationItems.DataKeys[e.NewSelectedIndex].Value ) );
            txtDescription.Text = c.Description;
            txtId.Text = c.Id.ToString();
        }

        protected void gvCancelationItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCancelationItems.PageIndex = e.NewPageIndex;
            LoadCancelationReasons();
        }
    }
}